package com.atguigu.gmall.pms.service.impl;

import com.atguigu.core.bean.PageVo;
import com.atguigu.core.bean.Query;
import com.atguigu.core.bean.QueryCondition;
import com.atguigu.gmall.pms.dao.AttrDao;
import com.atguigu.gmall.pms.dao.SkuInfoDao;
import com.atguigu.gmall.pms.dao.SpuInfoDao;
import com.atguigu.gmall.pms.dao.SpuInfoDescDao;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.SkuSaleFeign;
import com.atguigu.gmall.pms.service.ProductAttrValueService;
import com.atguigu.gmall.pms.service.SkuImagesService;
import com.atguigu.gmall.pms.service.SkuSaleAttrValueService;
import com.atguigu.gmall.pms.service.SpuInfoService;
import com.atguigu.gmall.pms.vo.ProductAttrValueVO;
import com.atguigu.gmall.pms.vo.SkuInfoVO;
import com.atguigu.gmall.pms.vo.SpuInfoVO;
import com.atguigu.gmall.sms.dto.SkuSaleDTO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private SpuInfoDescDao descDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuSaleFeign skuSaleFeign;

    @Override
    public PageVo queryPage(QueryCondition params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageVo(page);
    }

    @Override
    public PageVo querySpuPage(QueryCondition condition, Long catId) {
        // 封装分页条件
        IPage<SpuInfoEntity> page = new Query<SpuInfoEntity>().getPage(condition);

        // 封装查询条件
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        // 如果分类id不为0，要根据分类id查，否则查全部
        if (catId != 0) {
            wrapper.eq("catalog_id", catId);
        }
        // 如果用户输入了检索条件，根据检索条件查
        String key = condition.getKey();
        if (StringUtils.isNotBlank(key)) {
            wrapper.and(t -> t.like("spu_name", key).or().eq("id", key));
        }

        return new PageVo(this.page(page, wrapper));
    }


    @Override
    @GlobalTransactional
    public void saveSpuInfoVO(SpuInfoVO spuInfo) {

        //1.保存spu相关3张表
        Long spuId = saveSpuInfo(spuInfo);
        //1.2保存pms_spu_info_desc
        saveSpuInfoDesc(spuInfo, spuId);
        //1.3保存pms_product_attr_value
        saveSpuInfoBaseAttr(spuInfo, spuId);
        //保存sku相关信息
        saveSkuAndSale(spuInfo, spuId);
    }

    /**
     * 保存spu基本属性信息
     *
     * @param spuInfo
     * @param spuId
     */
    private void saveSpuInfoBaseAttr(SpuInfoVO spuInfo, Long spuId) {
        List<ProductAttrValueVO> baseAttrs = spuInfo.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(productAttrValueVO -> {
                productAttrValueVO.setSpuId(spuId);
                productAttrValueVO.setAttrSort(0);
                productAttrValueVO.setQuickShow(0);
                return productAttrValueVO;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntities);
        }
    }

    /**
     * 保存spu描述信息（图片）
     *
     * @param spuInfo
     * @param spuId
     */
    private void saveSpuInfoDesc(SpuInfoVO spuInfo, Long spuId) {
        List<String> spuImages = spuInfo.getSpuImages();
        if (!CollectionUtils.isEmpty(spuImages)) {
            SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
            descEntity.setSpuId(spuId);
            descEntity.setDecript(StringUtils.join(spuImages, ','));
            descDao.insert(descEntity);
        }
    }

    /**
     * 保存spu基本信息
     *
     * @param spuInfo
     */
    private Long saveSpuInfo(SpuInfoVO spuInfo) {
        //1.1保存pms_spu_spuinfo表
        spuInfo.setPublishStatus(1); // 默认是已上架
        spuInfo.setCreateTime(new Date());
        spuInfo.setUodateTime(spuInfo.getCreateTime());
        this.save(spuInfo);
        return spuInfo.getId();
    }

    /**
     * 保存sku相关信息及营销信息
     *
     * @param spuInfo
     */
    private void saveSkuAndSale(SpuInfoVO spuInfo, Long spuId) {
        //2.保存sku相关的3张表
        List<SkuInfoVO> skus = spuInfo.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
            return;
        }
        //2.1保存pms_sku_info
        skus.forEach(skuInfoVO -> {
            // 2.1. 保存sku基本信息
            // 品牌和分类的id需要从spuInfo中获取
            skuInfoVO.setBrandId(spuInfo.getBrandId());
            skuInfoVO.setCatalogId(spuInfo.getCatalogId());
            // 获取随机的uuid作为sku的编码
            skuInfoVO.setSkuCode(UUID.randomUUID().toString().substring(0, 10).toUpperCase());
            skuInfoVO.setSpuId(spuId);
            // 获取图片列表
            List<String> images = skuInfoVO.getImages();
            // 如果图片列表不为null，则设置默认图片
            if (!CollectionUtils.isEmpty(images)) {
                // 设置第一张图片作为默认图片
                skuInfoVO.setSkuDefaultImg(skuInfoVO.getSkuDefaultImg() == null ? images.get(0) : skuInfoVO.getSkuDefaultImg());
            }

            this.skuInfoDao.insert(skuInfoVO);
            // 获取skuId
            Long skuId = skuInfoVO.getSkuId();

            // 2.2. 保存sku图片信息
            if (!CollectionUtils.isEmpty(images)) {
                String defaultImage = images.get(0);
                List<SkuImagesEntity> skuImageses = images.stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setDefaultImg(StringUtils.equals(defaultImage, image) ? 1 : 0);
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgSort(0);
                    skuImagesEntity.setImgUrl(image);
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                this.skuImagesService.saveBatch(skuImageses);
            }

            // 2.3. 保存sku的规格参数（销售属性）
            List<SkuSaleAttrValueEntity> saleAttrs = skuInfoVO.getSaleAttrs();
            if (!CollectionUtils.isEmpty(saleAttrs)) {
                saleAttrs.forEach(saleAttr -> {
                    System.out.println(saleAttr.getAttrId());
                    // 设置属性名，需要根据id查询AttrEntity
                    saleAttr.setAttrName(this.attrDao.selectById(saleAttr.getAttrId()).getAttrName());
                    saleAttr.setAttrSort(0);
                    saleAttr.setSkuId(skuId);
                });
                //saleAttrs.forEach(skuSaleAttrValueEntity -> skuSaleAttrValueEntity.setSkuId(skuId));
                this.skuSaleAttrValueService.saveBatch(saleAttrs);
            }
            //3.保存营销信息3张表
            // 3. 保存营销相关信息，需要远程调用gmall-sms
            SkuSaleDTO skuSaleDTO = new SkuSaleDTO();
            BeanUtils.copyProperties(skuInfoVO, skuSaleDTO);
            skuSaleDTO.setSkuId(skuId);
            this.skuSaleFeign.saveSkuSaleInfo(skuSaleDTO);
        });
    }


}
